package com.me.forum.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.me.forum.domain.Page;
import com.me.forum.domain.User;
import com.me.forum.request.PageRequest;
import com.me.forum.service.IPageService;
import com.me.forum.utils.components.model.IModel;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/page")
public class PageController {
	@Autowired
	private IPageService pageService;
	
	@PostMapping("")
	public IModel save(PageRequest preq, IModel model, HttpSession session){
		preq.setUserId(((User)session.getAttribute("user")).getId().toString());
		return model.success(pageService.addPage(preq));
	}
	
	/**
	*@description:通过id获取帖子
	*@author:LWP
	*@createTime:2020-04-26 19:44
	*/
	@GetMapping("/{id}")
	public Map<String, Object> getPage(@PathVariable String id) {
		Map<String, Object> stringMap = new HashMap<>();
		Page page = pageService.findById(id);
		stringMap.put("success", page != null);
		stringMap.put("page", page);
		return stringMap;
	}

	//获取所有帖子 by Orange
	@GetMapping
	public Object getAll(PageRequest preq, String page, String size){
		IPage<Page> pages =  pageService.getAll(preq,page,size);
		var map = new HashMap<String ,Object>();
		map.put("success",pages!=null);
		map.put("pages",pages);
		return map;
	}

	//删除帖子  delete
	@DeleteMapping
	public IModel deletePage(String id, IModel model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Page page = pageService.findById(id);
		if (!user.getId().equals(page.getUserId()))
			return model.success(false);
		return model.success(pageService.delete(id));
	}
}
